<template>
  <div>
    <!-- <h1>RecordView</h1> -->
    <!--  -->
    <div v-if="formData" class="wrapper">
      <el-form label-width="80px">
        <el-form-item label="呼号">
          <el-input
            v-model="formData.acid"
            placeholder="必填"
            @input="handleInput"
          />
        </el-form-item>
        <el-form-item label="公司">
          <el-select v-model="formData.company" placeholder="请选择">
            <el-option
              v-for="company in optionData.companies"
              :label="company.label"
              :value="company.value"
            >
              <span style="float: left">{{ company.label }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
              >
                {{ company.value }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="席位">
          <el-select
            v-model="formData.seat"
            placeholder="请选择"
            @change="handleSeatChange"
          >
            <el-option
              v-for="seat in optionData.seats"
              :label="seat.name"
              :value="seat.name"
            >
              <span style="float: left">{{ seat.name }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
              >
                {{ seat.frequency }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="频率">
          <!-- <el-input-number v-model="formData.frequency" :min="110" :max="140" /> -->
          <el-select v-model="formData.frequency" placeholder="请选择">
            <el-option
              v-for="seat in optionData.seats"
              :label="seat.frequency"
              :value="seat.frequency"
            >
              <span style="float: left">{{ seat.frequency }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
              >
                {{ seat.name }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件时间">
          <el-date-picker
            v-model="formData.dateTime"
            type="date"
            :clearable="false"
            style="width: 160px"
            @change="handleDateTimeChange"
          />
          <span style="padding: 0 8px; color: var(--el-color-info-light-5)"
            >-</span
          >
          <el-time-picker
            v-model="formData.dateTime"
            format="HH:mm"
            :clearable="false"
            style="width: 120px"
            @change="handleDateTimeChange"
          />
        </el-form-item>
        <el-form-item label="指令速度">
          <el-select v-model="formData.speedCleared" placeholder="请选择">
            <el-option
              v-for="speed in optionData.speeds"
              :label="speed + 'kt'"
              :value="speed"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="实际速度">
          <el-select v-model="formData.speedExecuted" placeholder="请选择">
            <el-option
              v-for="speed in optionData.speeds"
              :label="speed + 'kt'"
              :value="speed"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="飞行阶段">
          <el-select
            v-model="formData.stage"
            placeholder="请选择"
            @change="handleStageChange"
          >
            <el-option
              v-for="stage in optionData.stages"
              :label="stage.label"
              :value="stage.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="五边位置" v-if="formData.stage == 3">
          <el-select v-model="formData.finalPosition" placeholder="请选择">
            <el-option
              v-for="position in optionData.finalPositions"
              :label="position + 'nm'"
              :value="position"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="影响程度">
          <el-select
            v-model="formData.effect"
            placeholder="请选择"
            @change="handleEffectChange"
          >
            <el-option
              v-for="effect in optionData.effects"
              :label="effect.label"
              :value="effect.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="中止进近"
          v-if="formData.effect == 3 && formData.stage == 3"
        >
          <el-select v-model="formData.missedApproach" placeholder="请选择">
            <el-option
              v-for="option in optionData.missedApproachOptions"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="补充描述">
          <el-input
            v-model="formData.description"
            :rows="4"
            type="textarea"
            placeholder="选填, 如有需要补充的信息请填写"
            resize="none"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button link @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- <pre>{{ formData }}</pre> -->
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, h } from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import useSeatStore from "@/store/seat.js";
import OptionDataStatics from "./OptionDataStatics.js";

const seatStore = useSeatStore();
const formData = ref(null);
const optionData = ref();

const handleInput = (value) => {
  formData.value.acid = value.toUpperCase();
  if (value.length > 2) {
    value = value.toUpperCase();
    // let matched = false;
    let chars = value.substring(0, 3);
    let matched = optionData.value.companies.filter(
      (cell) => cell.value == chars
    );
    if (matched.length > 0) {
      formData.value.company = chars;
    } else {
      formData.value.company = "其他";
    }
  } else {
    formData.value.company = "其他";
  }
};

const handleSeatChange = (val) => {
  let matched = optionData.value.seats.filter((seat) => seat.name == val);
  if (matched.length > 0) {
    formData.value.frequency = matched[0].frequency;
  }
};
const handleDateTimeChange = (val) => {
  formData.value.moment = dayjs(val).format("YYYY-MM-DD HH:mm:ss");
};

const handleCheck = () => {
  let result = new Array();
  if (formData.value.acid.length < 4) {
    result.push("呼号长度不少于 4 个字符");
  }
  if (formData.value.acid.length > 10) {
    result.push("呼号长度不多于 10 个字符");
  }
  if (dayjs().isBefore(formData.value.dateTime)) {
    result.push("请选择正确的事发时间 (不应晚于当前时间)");
  }
  if (formData.value.speedCleared == formData.value.speedExecuted) {
    result.push("指令速度不应与实际速度相同");
  }
  if (
    formData.value.description.length > 0 &&
    formData.value.description.length < 8
  ) {
    result.push("如果需要补充描述, 不得少于 8 个字符");
  }
  if (result.length > 0) {
    ElMessageBox({
      title: "内容有误",
      type: "error",
      message: h(
        "div",
        null,
        result.map((msg) => h("p", null, msg))
      ),
      type: "error",
    });
    return false;
  }
  if (formData.value.stage != 3) {
    formData.value.finalPosition = 0;
    formData.value.missedApproach = 0;
  }
  if (formData.value.effect != 3) {
    formData.value.missedApproach = 0;
  }
  return true;
};
const handleSubmit = () => {
  if (handleCheck()) {
    ElMessageBox.confirm("提交后将无法修改数据", "确认提交?", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }).then(() => {
      axios
        .post("api/journal_speed.php", {
          method: "record",
          payload: formData.value,
        })
        .then((response) => {
          console.log("SpeedDevidationRecord", response);
          if (response.data.status == 1) {
            ElNotification({
              title: "提交成功",
              type: "success",
            });
            initOptionData();
            initFormData();
          } else {
            ElNotification({
              title: "提交失败",
              type: "error",
              message: JSON.stringify(response.data),
            });
          }
        })
        .catch((error) => {
          console.error("SpeedDevidationRecord", error);
          ElNotification({
            title: "提交失败",
            type: "error",
            message: error.message,
          });
        });
    });
  }
};

const handleReset = () => {
  initOptionData();
  initFormData();
};

const initOptionData = () => {
  optionData.value = JSON.parse(JSON.stringify(OptionDataStatics));
  optionData.value.speeds = Array(20)
    .fill(null)
    .map((_, i) => 120 + i * 10);
  optionData.value.finalPositions = Array(20)
    .fill(null)
    .map((_, i) => 6 + i * 1);
  optionData.value.seats = seatStore.seatStatus
    .filter(
      (seat) => seat.orgGroup == "TMA" && seat.sectorYes && seat.frequency
    )
    .map((seat) => ({ name: seat.seatName, frequency: seat.frequency }));
  optionData.value.seats.push({ name: "其他", frequency: "其他" });
};

const initFormData = () => {
  formData.value = {
    acid: "",
    company: "其他",
    seat: "TM01",
    frequency: 124.85,
    dateTime: new Date(),
    moment: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    stage: 3,
    speedCleared: 160,
    speedExecuted: 180,
    effect: 0,
    description: "",
    // appendings
    finalPosition: 6,
    missedApproach: 0,
  };
};

const handleStageChange = (value) => {
  formData.value.missedApproach = 0;
  formData.value.finalPosition = value == 3 ? 6 : 0;
};

const handleEffectChange = (value) => {
  formData.value.missedApproach = 0;
};

onMounted(() => handleReset());
</script>

<style scoped>
.wrapper {
  width: 100%;
  max-width: 640px;
  margin-left: max(0px, calc(50vw - 540px));
}
</style>
